package com.leetcode.test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 两数之和
 *
 * @author tanghailan
 * @date 2021年10月16日 17:48
 */
public class TwoSumDemo {

  public static void main(String[] args) {
    int[] nums = new int[] {2, 4, 5, 7, 8};
    int target = 15;
    int[] result = twoSum1(nums, target);
    System.out.println(Arrays.toString(result));
  }

  public static int[] twoSum(int[] nums, int target) {
    // 遍历  暴力破解 ...
    for (int i = 0; i < nums.length; i++) {
      for (int j = i + 1; j < nums[i]; j++) {
        if (target - nums[i] == nums[j]) {
          return new int[] {i, j};
        }
      }
    }
    return null;
  }

  public static int[] twoSum1(int[] nums, int target) {
    // 遍历  暴力破解 ...
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
      int partnerNumber = target - nums[i];
      if (map.containsKey(partnerNumber)) {
        return new int[] {map.get(partnerNumber), i};
      }
      map.put(nums[i], i);
    }
    return null;
  }
}
